package com.iflytek.cosmo.ocr.common.core.worker;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import com.iflytek.cosmo.ocr.common.core.BeanHelper;
import com.iflytek.cosmo.ocr.common.core.station.AbstractStation;
import com.iflytek.cosmo.ocr.common.core.task.CompressTask;
import com.iflytek.cosmo.ocr.common.core.task.FormatTask;
import com.iflytek.cosmo.ocr.common.core.task.RecognizedTask;
import com.iflytek.cosmo.ocr.common.util.GsUtil;
import com.iflytek.cosmo.ocr.common.util.JSONUtil;
import com.iflytek.cosmo.ocr.model.domain.FileInfo;
import com.iflytek.cosmo.ocr.service.FileService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

/**
 * 一个处理格式的员工，是一个线程
 */
public class FormatWorker implements Runnable {
    /**
     * 日志记录器
     */
    private Logger logger = LoggerFactory.getLogger(FormatWorker.class);

    private RecognizedTask task;
    /**
     * 下一个工作台
     */
    private AbstractStation nextStation;

    public FormatWorker(RecognizedTask task, AbstractStation nextStation) {
        this.task = task;
        this.nextStation = nextStation;
    }

    @Override
    public void run() {
        FileService fileService = BeanHelper.getFileServiceBean();
        RecognizedTask cTask;

        FileInfo fileInfo = this.task.getFileInfo();
        if (null == fileInfo) {
            return;
        }
        logger.debug("开始格式处理任务, fileName: {}", fileInfo.getFileName());

        //如果是pdf格式的文件，则需要拆分成多个图片
        if ("pdf".equalsIgnoreCase(fileInfo.getFileType())) {
            // 加密pdf识别时, 密码暂时放到storePath
            String password = fileInfo.getFormatPath();
            splitePdf(fileInfo, ((FormatTask) task).getFileBytes(), password);
        }
        else {
            cTask = this.task;
            nextStation.add(cTask);
        }
    }


    private void splitePdf(FileInfo fileInfo, byte[] fileBytes, String password) {
        String fileId = fileInfo.getId();
        GsUtil gsUtil = BeanHelper.getGsUtil();

        List<File> files = gsUtil.pdf2Image(fileId, fileBytes, password, "pdf", "jpg", null);
        if (CollectionUtils.isEmpty(files)) {
            logger.warn("子页面拆分结果为空. fileId: {}", fileId);
            return;
        }

        int fileCount = files.size();
        logger.info("子页面拆分完成, pdfId: {}, size: {}, file:{}", fileId, fileCount, JSONUtil.toStrByDefault(files));

        File parentDic = null;
        for (int i = 0; i < fileCount; i++) {
            int pageNum = i + 1;
            File file = files.get(i);
            parentDic = file.getParentFile();
            try (OutputStream outputStream = new ByteArrayOutputStream();
                    FileInputStream fis = new FileInputStream(file)) {
                IOUtils.copy(fis, outputStream);

                CompressTask itemTask = new CompressTask();
                itemTask.setImageOutputStream(outputStream);
                itemTask.setParentFileInfo(fileInfo);

                //转出来的图片作为当前文件
                FileInfo currentFile = new FileInfo();
                String fileName = fileInfo.getFileName() + "_" + pageNum;
                currentFile.setFileName(fileName);
                itemTask.setIndex(pageNum);
                itemTask.setFileInfo(currentFile);
                itemTask.setFileType("pdf");
                nextStation.add(itemTask);
            }
            catch (Exception e) {
                logger.warn("PDF子页面拆分异常, pdfId: {}, index: {}, subPage: {}", fileId, i, file.getName(), e);
            } finally {
                FileUtils.deleteQuietly(file);
            }
        }

        try {
            FileUtils.deleteDirectory(parentDic);
        }
        catch (IOException e) {
            // mute
        }
    }
}
